package org.bonorsoft.modules.dingding.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.bonorsoft.modules.dingding.entity.SysUserRole;
import org.bonorsoft.modules.dingding.mapper.SysUserRoleMapper;
import org.bonorsoft.modules.dingding.service.ISysUserRoleService;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.List;

/**
 * @Description: 用户与角色关联
 * @Author: WilliamYe
 * @Date:   2020-11-13
 * @Version: V1.0
 */
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements ISysUserRoleService {

    @Override
    public void addUserRole(List<String> userIdList, List<Integer> labelIdList) {
        labelIdList.forEach(item -> userIdList.forEach( it -> {
            deleteRole(item, it);
            SysUserRole userRole = new SysUserRole();
            userRole.setUserId(it);
            userRole.setId(item);
            this.save(userRole);
        }));
    }

    @Override
    public void deleteUserRole(List<String> userIdList, List<Integer> labelIdList) {
        labelIdList.forEach(item -> userIdList.forEach( it -> deleteRole(item, it)));
    }

    private void deleteRole(Integer roleId, String userId){
        QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("USER_ID",userId).eq("id", roleId);
        this.remove(queryWrapper);
    }

    /**
     * 通过角色ID查询角色使用数量
     *
     * @param id 角色ID
     * @return 结果
     */
    public Integer countUserRoleByRoleId(Integer id) {
        QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        return this.count(queryWrapper);
    }
}
